package com.example.restatr.Atcivity.JobSearch;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.restatr.Atcivity.Main.MainActivity;
import com.example.restatr.Atcivity.JobSearch.Bean.JobProfessionBean;
import com.example.restatr.Atcivity.JobSearch.Bean.JobResumeBean;
import com.example.restatr.R;
import com.example.restatr.Tools;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class JobResumeAt extends AppCompatActivity {
    private Toolbar tb;
    private TextView barTitle;
    private EditText search;
    private TextView education;
    private TextView workHistory;
    private TextView expectPost;
    private TextView allText;

    private EditText money;
    private EditText address;
    private EditText individualResume;
    private ListView dialogList;
    private AlertDialog alertDialog;
    private List<String> titles = new ArrayList<>();
    private List<JobProfessionBean.RowsBean> jobProfessionBeans = new ArrayList<>();
    private JobResumeBean.DataBean data;
    private int posId;
    private boolean isExistResume = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_job_resume_at);

        tb = findViewById(R.id.toolbar);
        barTitle = findViewById(R.id.bar_Title);
        search = findViewById(R.id.search);
        education = findViewById(R.id.education);
        workHistory = findViewById(R.id.workHistory);
        expectPost = findViewById(R.id.expectPost);
        money = findViewById(R.id.money);
        address = findViewById(R.id.address);
        individualResume = findViewById(R.id.individualResume);
        Tools.SetBarTitle(tb, barTitle, "我的简历", search, this,false);
        tb.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.item1:
                        startActivity(new Intent(JobResumeAt.this, JobResumeAt.class));
                        break;
                    case R.id.item2:
                        startActivity(new Intent(JobResumeAt.this,JobDeliverList.class));
                        break;
                }
                return true;
            }
        });
        CreateDialog();
        GetProfession();
        allText = new TextView(this);
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.education:
                titles.clear();
                Collections.addAll(titles, "初中", "高中及中专", "大专", "本科", "硕士以上");
                dialogList.setAdapter(new JobDialogListAdapter());
                alertDialog.show();
                allText = education;
                break;
            case R.id.workHistory:
                titles.clear();
                Collections.addAll(titles, "应届毕业", "1年工作经验", "1-3年工作经验", "3-5年工作经验", "5-8年工作经验", "8年工作经验以上");
                dialogList.setAdapter(new JobDialogListAdapter());
                alertDialog.show();
                allText = workHistory;
                break;
            case R.id.expectPost:
                GetProfession();
                alertDialog.show();
                allText = expectPost;
                break;
            case R.id.mileageCommit:
                if (Tools.isEmptyText(education) && Tools.isEmptyText(workHistory) && Tools.isEmptyText(expectPost)
                        && Tools.isEmptyText(money) && Tools.isEmptyText(address) && Tools.isEmptyText(individualResume)) {
                    if (isExistResume) {
                        AlterResume();
                    } else {
                        AddResume();
                    }
                } else {
                    Toast.makeText(this, "不能为空", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    private void CreateDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View inflate = getLayoutInflater().inflate(R.layout.job_dailog_layout, null);
        dialogList = inflate.findViewById(R.id.List);
        alertDialog = builder.setView(inflate).create();
    }

    //新增用户简历
    private void AddResume() {
        new Thread(() -> {
            try {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("education", education.getText().toString());
                jsonObject.put("address", address.getText().toString());
                jsonObject.put("experience", workHistory.getText().toString());
                jsonObject.put("money", money.getText().toString() + "月/元");
                jsonObject.put("individualResume", individualResume.getText().toString());
                jsonObject.put("positionId", posId);
                String post = Tools.Post("/prod-api/api/job/resume", MainActivity.sp.getString("token", ""), jsonObject.toString());
                JSONObject jx = new JSONObject(post);
                String msg = jx.getString("msg");
                int code = jx.getInt("code");
                runOnUiThread(() -> {
                    Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
                    if (code == 200) {
                        finish();
                    }
                });
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }).start();
    }

    //获取职位列表
    private void GetProfession() {
        titles.clear();
        new Thread(() -> {
            String token = Tools.Get("/prod-api/api/job/profession/list", MainActivity.sp.getString("token", ""));
            JobProfessionBean jobProfessionBean = new Gson().fromJson(token, JobProfessionBean.class);
            jobProfessionBeans.addAll(jobProfessionBean.getRows());
            runOnUiThread(() -> {
                GetUserResumeInfo();
                for (int i = 0; i < jobProfessionBeans.size(); i++) {
                    titles.add(jobProfessionBeans.get(i).getProfessionName());
                }
                dialogList.setAdapter(new JobDialogListAdapter());
            });
        }).start();
    }

    //获取用户简历信息
    private void GetUserResumeInfo() {
        new Thread(() -> {
            String get = Tools.Get("/prod-api/api/job/resume/queryResumeByUserId/" + MainActivity.sp.getInt("userId", 0), MainActivity.sp.getString("token", ""));
            JobResumeBean jobResumeBean = new Gson().fromJson(get, JobResumeBean.class);
            data = jobResumeBean.getData();
            posId=data.getPositionId();
            if (jobResumeBean.getCode() == 200) {
                isExistResume = true;
                runOnUiThread(() -> {
                    education.setText(data.getEducation());
                    workHistory.setText(data.getExperience());
                    //根据id查询职位名称
                    JobProfessionBean.RowsBean rowsBean1 = jobProfessionBeans.stream().filter(rowsBean -> rowsBean.getId() == data.getPositionId()).findAny().orElse(null);
                    money.setText(data.getMoney());
                    address.setText(data.getAddress());
                    individualResume.setText(data.getIndividualResume());
                    expectPost.setText(rowsBean1.getProfessionName());
                });
            }
        }).start();
    }

    //修改用户简历
    private void AlterResume() {
        new Thread(() -> {
            try {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("id", data.getId());
                jsonObject.put("education", education.getText().toString());
                jsonObject.put("address", address.getText().toString());
                jsonObject.put("experience", workHistory.getText().toString());
                jsonObject.put("money", money.getText().toString());
                jsonObject.put("individualResume", individualResume.getText().toString());
                jsonObject.put("positionId", posId);
                String token = Tools.Put("/prod-api/api/job/resume", MainActivity.sp.getString("token", ""), jsonObject.toString());
                JSONObject jx = new JSONObject(token);
                String msg = jx.getString("msg");
                int code = jx.getInt("code");
                runOnUiThread(() -> {
                    Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
                    if (code == 200) {
                        finish();
                    }
                });
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }).start();
    }

    class JobDialogListAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return titles.size();
        }

        @Override
        public Object getItem(int position) {
            return titles.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            convertView = getLayoutInflater().inflate(R.layout.job_dialog_item_layout, null);
            TextView title = convertView.findViewById(R.id.text);
            title.setText(titles.get(position));
            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    alertDialog.dismiss();
                    allText.setText(titles.get(position));
                    posId = jobProfessionBeans.get(position).getId();
                }
            });
            return convertView;
        }
    }


}